#include "GameModule.h"
#include "ResourceSystem.h"
#include <sstream>

GameModule::GameModule(void)
{
	
}

GameModule::GameModule( const std::string& filename )
{
	m_settings.Load(filename);
}
GameModule::~GameModule(void)
{
}

void GameModule::OnLoad()
{
	Module::OnLoad();
	m_world.GetTileMgr().FreeLevel();
	m_world.GetTileMgr().SetMapSize(150,150);
	m_world.GetTileMgr().LoadLevel();
	m_world.GetTileMgr().SetCamera(&m_camera);
	m_camera.SetSize(sf::Vector2f(800,600));
	m_world.SetWindow(m_window);  //m_window should be already set by the engine
	TileManager& tilemgr = m_world.GetTileMgr();
	m_camera.SetLimits(sf::Vector2f(0,tilemgr.GetMapSize().x * tilemgr.GetTileSize().x), 
		sf::Vector2f(0,tilemgr.GetMapSize().y * tilemgr.GetTileSize().y));

	m_camera.SetPos(5000,0);

	cursor.SetImage(ResourceSystem::GetImage("cursor001.bmp"));
	cursor.SetHotspot(27,40);
	if(m_window) m_window->ShowMouseCursor(false);

}

void GameModule::OnLoop(float diff)
{
	if(!m_window) 
		return;
	sf::Clock t;
	sf::String str;
	std::stringstream s;

	static int frame = 0;
	static int lastFps = 0;
	static float timediff = 0;

	frame++;
	timediff += diff;
	if(timediff > 1000) {
		lastFps = frame;
		timediff = 0;
		frame = 0;
	}
	m_window->Clear();
	m_world.Update(diff);
	const sf::Input& input = m_window->GetInput();
	if(input.IsKeyDown(sf::Key::Left)) {
		m_camera.Move(-.50f*diff,0);
	} else if(input.IsKeyDown(sf::Key::Right)) {
		m_camera.Move(.5f*diff,0);
	}
	sf::Vector2f pos = m_window->ConvertCoords(input.GetMouseX(),input.GetMouseY());
	cursor.SetPos(pos);
	s << "fps: "<< lastFps;
	str.SetPosition(650,0);
	str.SetText(s.str().c_str());
	m_window->Draw(str);
	cursor.Draw(m_window);
	m_window->Display();
}

void GameModule::OnClose()
{
	Module::OnClose();
}